package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import net.lcheng.model.OOrderRefund;
import net.lcheng.model.User;
import net.lcheng.service.ShoppingService;
import net.lcheng.service.TradeManageService;
import net.lcheng.service.UserService;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.shop.vo.UserSendGoodsModel;
import net.lcheng.utils.OorderRefund2OrderRefundModel;
import net.lcheng.vo.OrderRefundModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.NamedBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * Created by LV on 2016/7/22.
 */
@Controller
public class UserRefundOrderManageController {

    @Autowired
    private UserService userService;
    @Autowired
    private TradeManageService tradeManageService;
    @Autowired
    private ShoppingService shoppingService;

    /**
     * 用户获取指定店铺退单列表
     * @param model 模型
     * @param shopId 店铺Id
     * @return String
     */
    @RequestMapping(value = "/userRefundOrder/getAllRefundOrderByShopId",method = RequestMethod.GET)
    public String getAllRefundOrderByShopId(Model model, @RequestParam("sid") int shopId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            /**获取当前用户*/
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSON.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (user!=null){
                //获取所有退单
                List<OOrderRefund> orderRefundList=tradeManageService.getAllRefundOrders(shopId,user.getUserId());
                List<OrderRefundModel> orderRefundModelList= OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefundList);
                model.addAttribute("orderRefundModelList",orderRefundModelList);
                model.addAttribute("shopId",shopId);
                return "user_refund_orders/refund_all_orders";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 用户根据不同的状态获取指定店铺的退单列表
     * @param model 模型
     * @param shopId 店铺Id
     * @param status 订单状态
     * @return String
     */
    @RequestMapping(value = "/userRefundOrder/getAllRefundOrderByStatus",method = RequestMethod.GET)
    public String getAllRefundOrderByStatus(Model model, @RequestParam("sid") int shopId,@RequestParam("status") int status){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            /**获取当前用户*/
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSON.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (user!=null){
                //获取所有退单
                List<OOrderRefund> orderRefundList=tradeManageService.getAllRefundOrders(shopId,user.getUserId(),status);
                List<OrderRefundModel> orderRefundModelList= OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefundList);
                model.addAttribute("orderRefundModelList",orderRefundModelList);
                model.addAttribute("status",status);
                model.addAttribute("shopId",shopId);
                return "/user_refund_orders/refund_all_orders_status";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 买家取消退单申请
     * @param orderRefundId 需要退单的Id
     * @return String
     */
    @RequestMapping(value = "/userRefundOrder/cancelRefundOrder",method = RequestMethod.GET)
    public String cancelRefundOrder(@RequestParam("orId") String orderRefundId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取退单信息
            if (orderRefundId!=null&&!orderRefundId.equals("")) {
                OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                orderRefund.setOrderStatus(-1);
                orderRefund.setOrderCancelDescription("买家主动取消");
                orderRefund.setModifyOn(new Date());

                int status=tradeManageService.cancelOrderRefundByBuyer(orderRefund);
                if (status>0)
                    return "redirect:/userRefundOrder/getAllRefundOrderByShopId?sid="+orderRefund.getWxShopShopId();
                else
                    return "redirect:/error";
            }
            return "redirect:/error";

        }
        return "redirect:/login";
    }

    /**
     * 买家发货（邮寄需要退的货）
     * @param model 模型
     * @param orderRefundId 退货订单主键
     * @return String
     */
    @RequestMapping(value = "/userRefundOrder/refundGoodsByUser",method = RequestMethod.GET)
    public String refundGoodsByUser(Model model,@RequestParam("orId") String orderRefundId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderRefundId != null && !orderRefundId.equals("")){
                //获取退货订单信息
                OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                //解析订单商品Json串
                OrderRefundModel orderRefundModel=OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefund);
                model.addAttribute("orderRefund",orderRefund);
                model.addAttribute("orderRefundModel",orderRefundModel);
            return "/user_refund_orders/user_refund_goods";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存退还货物的快递信息
     * @param model 模型
     * @param goodsModel vo
     * @param result 验证结果
     * @return String
     */
    @RequestMapping(value = "/userRefundOrder/savingShippingInformation",method = RequestMethod.POST)
    public String savingShippingInformation(Model model,@Valid @ModelAttribute("goodsModel") UserSendGoodsModel goodsModel, BindingResult result){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (result.hasErrors()) {
                if (goodsModel != null){
                    //获取退货订单信息
                    OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(goodsModel.getRefundOrderId());
                    //解析订单商品Json串
                    OrderRefundModel orderRefundModel=OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefund);
                    model.addAttribute("orderRefund",orderRefund);
                    model.addAttribute("orderRefundModel",orderRefundModel);
                    return "/user_refund_orders/user_refund_goods";
                }
                return "redirect:/error";
            }
            //验证通过
            if (goodsModel!=null) {
                OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(goodsModel.getRefundOrderId());
                //填充快递信息
                orderRefund.setShippingCompanyCode(goodsModel.getShippingCode());
                orderRefund.setShippingCompanyName(goodsModel.getShippingName());
                orderRefund.setShippingTrackingNumber(goodsModel.getShippingNum());

                int status=shoppingService.refundGoodsByUser(orderRefund);
                if (status>0)
                    return "redirect:/userRefundOrder/getAllRefundOrderByShopId?sid="+orderRefund.getWxShopShopId();
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }
}
